<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <!-- <script src="js/vue.js"></script> -->
    <script src="../../js/vue.js"></script>
    <link rel="stylesheet" href="../../element-ui/lib/theme-chalk/index.css">


    <script src="../../element-ui/lib/index.js"></script>
    <script src="../../js/axios-0.18.0.js"></script>

</head>
<style>

</style>

<body>

<div id="app">

    <el-button
            style="background-color: black;color: white"
            type="primary"
            @click="showAddBookDialog()"
    >
        + 添加图书
    </el-button>


    <el-input v-model="searchText" placeholder="请输入搜索内容" style="width: 200px"  @keyup.enter="handleSearch"></el-input>
    <el-select v-model="searchType" placeholder="选择搜索类型" style="width: 150px">
        <el-option label="按书名搜索" value="name"></el-option>
        <el-option label="按作者搜索" value="author"></el-option>
        <el-option label="按分类搜索" value="type"></el-option>
        <el-option label="按图书号搜索" value="card"></el-option>
    </el-select>
    <el-button type="primary" @click="handleSearch">搜索</el-button>


    <el-button
            style="background-color: red;color: white;float:right;margin-right: 50px"
            type="primary"
            @click="batchDelete()"
    >
        批量删除
    </el-button>

    <el-table style="padding: 20px"
              :data="tableData"
              stripe

              @selection-change="handleSelectionChange"

    >


        <el-table-column type="selection" width="55"></el-table-column>
        <!--          图书分类名称）-->
        <el-table-column
                prop="name"
                label="图书名"
        >
        </el-table-column>
        <el-table-column
                prop="card"
                label="图书号"
        >
        </el-table-column>
        <el-table-column
                prop="author"
                label="作者"
        >
        </el-table-column>
        <el-table-column
                prop="num"
                label="数量"
        >
        </el-table-column>
        <el-table-column
                prop="press"
                label="出版社"
        >
        </el-table-column>

        <el-table-column
                prop="type"
                label="分类类型"
        >
        </el-table-column>

<!--        <el-table-column label="状态">-->
<!--            <template slot-scope="scope">-->
<!--                &lt;!&ndash; 根据 status 的值动态渲染不同的内容 &ndash;&gt;-->
<!--                <span v-if="scope.row.status === 2">未借出</span>-->
<!--                <span v-else>借阅中</span>-->
<!--            </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column-->
<!--                prop="status"-->
<!--                label="状态"-->
<!--        >-->
<!--        </el-table-column>-->


        <el-table-column
                label="操作"
                width="160"
                align="center"
        >
            <template slot-scope="scope">
                <el-button
                        type="text"
                        size="small"
                        class="blueBug"
                        @click="editHandle(scope.row)"
                >
                    修改
                </el-button>
                <el-button
                        type="text"
                        size="small"
                        class="delBut non"
                        @click="deleteHandle(scope.row)"
                >
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-dialog
            title="添加图书"
            :visible.sync="addBookDialogVisible"
            width="30%"
            @close="resetAddBookForm"
    >
        <!-- 图书表单内容 -->
        <el-form :model="addBookForm" ref="addBookForm" label-width="80px">
            <el-form-item label="图书名" prop="name" :rules="[
    { required: true, message: '图书名不能为空', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.name" ></el-input>
            </el-form-item>

            <el-form-item label="图书号" prop="card" :rules="[
    { required: true, message: '图书号不能为空', trigger: 'blur' },
   { pattern: /^\d+$/, message: '图书号必须为数字', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.card" ></el-input>
            </el-form-item>


            <el-form-item label="作者" prop="author" :rules="[
    { required: true, message: '作者不能为空', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.author"></el-input>
            </el-form-item>

            <el-form-item label="数量" prop="num" :rules="[
    { required: true, message: '请输入数量', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.num" type="number"></el-input>
            </el-form-item>

            <el-form-item label="出版社" prop="press" :rules="[
    { required: true, message: '出版社不能为空', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.press"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="type" :rules="[
    { required: true, message: '请选择分类', trigger: 'blur' }
]">
                <el-select v-model="addBookForm.type">
                    <el-option
                            v-for="category in bookCategories"
                            :key="category.tid"
                            :label="category.name"
                            :value="category.name">
                    </el-option>
                </el-select>
            </el-form-item>

        </el-form>

        <!-- 操作按钮 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="addBookDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddBookForm">提交</el-button>
            <el-button type="primary" @click="submitAndContinue">提交并继续添加</el-button>
        </span>
    </el-dialog>


    <el-dialog
            title="修改图书"
            :visible.sync="editBookDialogVisible"
            width="30%"
            @close="resetAddBookForm"
    >
        <!-- 图书表单内容 -->
        <el-form :model="addBookForm" ref="addBookForm" label-width="80px">
            <el-form-item label="图书名" prop="name" :rules="[
    { required: true, message: '图书名不能为空', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.name" ></el-input>
            </el-form-item>

            <el-form-item label="图书号" prop="card" :rules="[
    { required: true, message: '图书号不能为空', trigger: 'blur' },
   { pattern: /^\d+$/, message: '图书号必须为数字', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.card" ></el-input>
            </el-form-item>


            <el-form-item label="作者" prop="author" :rules="[
    { required: true, message: '作者不能为空', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.author"></el-input>
            </el-form-item>

            <el-form-item label="数量" prop="num" :rules="[
    { required: true, message: '请输入数量', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.num" type="number"></el-input>
            </el-form-item>

            <el-form-item label="出版社" prop="press" :rules="[
    { required: true, message: '出版社不能为空', trigger: 'blur' }
]">
                <el-input v-model="addBookForm.press"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="type" :rules="[
    { required: true, message: '请选择分类', trigger: 'blur' }
]">
                <el-select v-model="addBookForm.type">
                    <el-option
                            v-for="category in bookCategories"
                            :key="category.tid"
                            :label="category.name"
                            :value="category.name">
                    </el-option>
                </el-select>
            </el-form-item>

        </el-form>

        <!-- 操作按钮 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="editBookDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submiteditBookForm">提交</el-button>
        </span>
    </el-dialog>



    <el-pagination

            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="counts"
            @size-change="handleSizeChange"
            :current-page.sync="page"
            @current-change="handleCurrentChange"
    ></el-pagination>
</div>

</body>
<!--<script src="../../api/member.js"></script>-->

<script>

    let myVue = new Vue({
        el: '#app',
        data() {
            return {
                input: '',
                counts: 0,
                page: 1,
                pageSize: 10,
                tableData: [],
                addBookDialogVisible: false, // 控制添加图书对话框的显示与隐藏
                editBookDialogVisible:false,
                addBookForm: {
                    bid: '',
                    name: '',
                    card: '',
                    author: '',
                    num: '1',
                    press: '',
                    type: ''
                },
                bookCategories: [], // 存储已有的图书分类列表
                selectedRows: [],
                searchText: '', // 搜索文本
                searchType: 'name', // 默认搜索类型为书名

            }
        },
        created() {
            this.init();
            this.fetchBookCategories(); // 发送异步请求获取图书分类列表

        },
        methods: {
            handleSearch() {
                this.page = 1; // 重置页码为1
                this.init(); // 执行搜索操作
            },
            async init() {
                // axios.get("/book_info/page?page=" + this.page + "&pageSize=" + this.pageSize + "&name=" + this.input).then(res => {
                //     this.tableData = res.data.data.records;
                //     this.counts = res.data.data.total;
                // })

                let params = {
                    page: this.page,
                    pageSize: this.pageSize
                };

                // 根据搜索类型设置请求参数
                if (this.searchText) {
                    if (this.searchType === 'name') {
                        params.name = this.searchText;
                    } else if (this.searchType === 'author') {
                        params.author = this.searchText;
                    }else if (this.searchType === 'type'){
                        params.type = this.searchText;
                    }else if (this.searchType === 'card'){
                        params.card = this.searchText;
                    }
                }
                //按照分类搜索

                axios.get("/book_info/page", { params })
                    .then(res => {
                        this.tableData = res.data.data.records;
                        this.counts = res.data.data.total;
                    })
            },
            handleQuery() {
                this.page = 1;
                this.init();
            },
            handleSizeChange(val) {
                this.pageSize = val
                this.init()
            },
            handleCurrentChange(val) {
                this.page = val
                this.init()
            },
            showAddBookDialog() {
                this.addBookDialogVisible = true; // 显示添加图书对话框
            },
            resetAddBookForm() {
                this.$refs['addBookForm'].resetFields(); // 重置添加图书表单
            },
            submitAddBookForm() {
                this.$refs['addBookForm'].validate(valid => {
                    if (valid) {
                        // console.log(this.addBookForm)
                        // 向服务器发送 POST 请求以添加新图书
                        axios.post("/book_info", this.addBookForm)
                            .then(res => {
                                if (res.data.code === 1) {
                                    // 添加成功，关闭对话框并重新加载数据
                                    this.addBookDialogVisible = false;
                                    this.init();
                                    this.$message.success('添加图书成功！');
                                } else {
                                    // 添加失败，显示错误信息
                                    this.$message.error(res.data.msg || '添加图书失败！');
                                }
                            })
                            .catch(err => {
                                // 请求失败，显示错误信息
                                this.$message.error('请求出错了：' + err);
                            });
                    } else {
                        // 表单校验不通过，不执行提交操作
                        return false;
                    }
                });
            },

            async fetchBookCategories() {
                try {
                    const response = await axios.get("/book/book_categories");
                    this.bookCategories = response.data.data; // 将获取到的分类列表保存到变量中
                } catch (error) {
                    console.error('获取图书分类列表失败：', error);
                }
            },
            deleteHandle(obj) {
                // console.log(obj);

                this.$confirm('此操作将永久删除该图书, 是否继续?', '提示', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                    'type': 'warning'
                }).then(() => {
                    console.log(obj)

                    axios.delete("/book_info?bids=" + obj.bid).then(res => {
                        if (res.data.code === 1) {
                            this.$message.success('删除成功！')
                            this.handleQuery()
                        } else {
                            this.$message.error(res.data.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                })
                // console.log('删除');
            },
            batchDelete() {
                if (this.selectedRows.length === 0) {
                    this.$message.warning('请选择要删除的数据！');
                    return;
                }

                this.$confirm('此操作将永久删除所选图书, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 执行批量删除操作
                    const bids = this.selectedRows.map(row => row.bid);
                    console.log(bids.toString())
                    axios.delete("/book_info?bids=" + bids.toString()).then(res => {
                        if (res.data.code === 1) {
                            this.$message.success('批量删除成功！');
                            this.handleQuery();
                        } else {
                            this.$message.error(res.data.msg || '操作失败');
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err);
                    });
                });
            },

// 监听复选框选择事件，更新选中的数据
            handleSelectionChange(val) {
                // this.selectedRows = this.selectedRows.join(",") ;
                this.selectedRows = val || [];
                // console.log("val=" + val);

            },
            submitAndContinue() {
                this.$refs['addBookForm'].validate(valid => {
                    if (valid) {
                        axios.post("/book_info", this.addBookForm)
                            .then(res => {
                                if (res.data.code === 1) {
                                    this.$message.success('添加图书成功！');
                                    this.resetAddBookForm(); // 清空表单内容
                                    this.handleQuery();
                                } else {
                                    this.$message.error(res.data.msg || '添加图书失败！');
                                }
                            })
                            .catch(err => {
                                this.$message.error('请求出错了：' + err);
                            });
                    } else {
                        return false;
                    }
                });
            },
            editHandle(bookInfo) {
                // 将选中行的图书信息传递给表单，以便进行编辑
                this.addBookForm = { ...bookInfo };
                // 打开添加图书对话框，并设置标题为“编辑图书”
                this.editBookDialogVisible = true;
            },
            submiteditBookForm(){
                this.$refs['addBookForm'].validate(valid => {
                    if (valid) {
                        console.log(this.addBookForm)
                        axios.put("/book_info", this.addBookForm)
                            .then(res => {
                                if (res.data.code === 1) {
                                    // 添加成功，关闭对话框并重新加载数据
                                    this.editBookDialogVisible = false;
                                    this.init();
                                    this.$message.success('修改图书成功！');
                                } else {
                                    this.$message.error(res.data.msg || '修改图书失败！');
                                }
                            })
                            .catch(err => {
                                // 请求失败，显示错误信息
                                this.$message.error('请求出错了：' + err);
                            });
                    } else {
                        // 表单校验不通过，不执行提交操作
                        return false;
                    }
                });
            }

        }
    })


</script>


</html>